package cn.turboinfo.fuyang.api.domain.mini.usecase.my;

import cn.turboinfo.fuyang.api.domain.common.handler.address.AddressDataFactory;
import cn.turboinfo.fuyang.api.domain.common.service.address.AddressService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.fo.address.ViewAddressFO;
import cn.turboinfo.fuyang.api.entity.common.pojo.address.Address;
import cn.turboinfo.fuyang.api.entity.common.pojo.address.QAddress;
import cn.turboinfo.fuyang.api.entity.mini.fo.my.MiniMyAddressListItem;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.api.request.QPage;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import net.sunshow.toolkit.core.qbean.api.request.QSort;
import net.sunshow.toolkit.core.qbean.api.response.QResponse;
import net.sunshow.toolkit.core.qbean.helper.component.mapper.BeanMapper;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;

/**
 * 我的地址
 *
 * @author sunshow
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class MiniMyAddressListUseCase extends AbstractUseCase<MiniMyAddressListUseCase.InputData, MiniMyAddressListUseCase.OutputData> {

    private final AddressService addressService;

    private final AddressDataFactory addressDataFactory;

    @Override
    protected OutputData doAction(InputData inputData) {
        Long userId = inputData.getUserId();
        QPage requestPage = inputData.getRequestPage();

        QRequest request = QRequest.newInstance()
                .filterEqual(QAddress.userId, userId);

        // 按创建时间降序排序
        requestPage.addOrder(QAddress.createdTime, QSort.Order.DESC);

        QResponse<Address> addressQResponse = addressService.findAll(request, requestPage);

        QResponse<MiniMyAddressListItem> addressList = addressQResponse.map(address ->

                {
                    addressDataFactory.maskInfo(address);

                    return MiniMyAddressListItem.builder()
                            .address(BeanMapper.map(address, ViewAddressFO.class))
                            .build();
                }
        );

        return OutputData.builder()
                .addressList(addressList)
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        /**
         * 用户ID
         */
        @NotNull(message = "用户ID不能为空")
        private Long userId;

        @NotNull(message = "分页参数不能为空")
        private QPage requestPage;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {

        /**
         * 我的地址列表
         */
        private QResponse<MiniMyAddressListItem> addressList;

    }
}
